<?php

namespace app\admin\controller;

use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords as Income;
use app\api\model\Privatechat;
use think\Db;
use Vectorface\Whip\Whip;

class CustomerUserService extends Common
{
    public function topupPrev()
    {
        $user_id = input('user_id');
        $user_id = intval($user_id);
        
        if (request()->isAjax()) {
            
            $post = input('post.');
            
            if (!$user_id) {
                return ['err' => '用户不存在' . $user_id];
            }
            
            $user = Db::name('user')->find($user_id);
            
            if (!$user) {
                return ['err' => '用户不存在'];
            }
            
            
            $current_time = time();
            
            $admin = session('admin', '', 'mmjtAdmin');

            if ($post['money'] > 99999) {
                return ['err' => '金额填写不得超过 99999'];
            }
            
            Db::name('customer_service_userup')->insert([
                'admin_id' => $admin['id'],
                'user_id' => $user_id,
                'channel' => $post['channel'],
                'toward' => $post['toward'],
                'money' => $post['money'],
                'ip' => (new Whip())->getValidIpAddress(),
                'os' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'data' => json_encode(['content' => $post['content']]),
                'create_time' => $current_time,
                'update_time' => $current_time
            ]);
            
            $data = ['ret' => '成功'];
            
        } else {
            if ($user_id) {
                $user = Db::name('user')->find($user_id);

                if (!$user) {
                    $this->error('用户不存在');
                }
                
                $this->assign('name', $user);
                $data = $this->fetch();
            } else {
                $this->error('参数错误');
            }
        }
        return $data;
    }
    
    public function topupPrevRecords()
    {
        // $where = ['channel' => 2, 'toward' => 1];
        $where = [];
        
        $status = input('status');
        if ($status !== null) {
            $where['status'] = $status;
        }
        
        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if (in_array($search_type, ['user_id'])) {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $data = Db::name('customer_service_userup')->master()->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function ($item, $key) {
            $item['data'] = json_decode($item['data'], true);
            $item['count'] = Db::name('customer_service_userup')->where(['user_id'=>$item['user_id'],'status'=>1])->count();
            return $item;
        });

        $data_array = $data->toArray()['data'];
        
        $uids = [];
        foreach ($data_array as $item) {
            if ($item['user_id']) {
                $uids[] = $item['user_id'];
            }
        }
        
        $uids = array_unique($uids);
        $users = Db::name('user')->where(['id' => ['in', $uids]])->column('id, name');
        
        $this->assign('users', $users);
        
        $this->assign('status', $status);
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        
        return $this->fetch();
    }
    
    public function topupPrevAdd()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            
            $post = input('post.');
            
            if ($id) {
                $records = Db::name('customer_service_userup')->master()->where(['id' => $id, 'status' => 0])->find();
                if (!$records) return ['err' => '记录不存在'];
                
                if ($post['status'] == 1) {
                    $user = Db::name('user')->master()->find($records['user_id']);
                    if ($user) {
                        $data = json_decode($records['data'], true);
                        if($records['channel'] == 2){
                            $type = $records['toward']==1 ? 0 : 1;
                            if($records['toward'] == 0 && $records['money'] > $user['score']){
                                return ['err' => '积分不足'];
                            }
                            if($records['toward']){
                                Privatechat::notice($records['user_id'], $data['content'] . ' 已处理');
                            }
                            Income::index($records['user_id'], 0, $records['money'], $data['content'], 1, '', $type);
                        }else{
                            if($records['toward'] == 0 && $records['money'] > $user['volley']){
                                return ['err' => '金币不足'];
                            }
                            if($records['toward']){
                                Privatechat::notice($records['user_id'], $data['content'] . ' 已处理');
                            }
                            Balance::index($records['user_id'], $records['money'], $data['content'], $records['toward']);

                            // if($records['toward']){
                            //     $uids = _getAllUser($records['user_id']);
                            //     $rechargecount = Db::name('topup')->where(['fk_userid'=>['in', $uids], 'state'=>1])->fetchSql(false)->sum('price');
                            //     if($rechargecount + ($records['money'] / 5) >= 4000){
                            //         $parent = Db::name('user')->where(['id'=>$records['user_id']])->value('yqr');
                            //         if($parent){
                            //             $parent = Db::name('user')->where(['yqm'=>$parent])->value('id');
                            //             if($parent){
                            //                 Privatechat::notice($parent, '禁止用户充值的比较高还在解锁，一经发现将冻结积分');
                            //             }
                            //         }
                            //     }
                            // }
                        }
                    }
                }
                $db = Db::name('customer_service_userup')->where('id', $id)->update(['status' => $post['status'], 'update_time' => time()]);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }

    public function topupPrevDel()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = Db::name('customer_service_userup')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
}
